package cn.tedu.smartos.base.interceptor;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.base.utils.user.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        token = token.substring(7); // 去掉"Bearer "前缀

        if (!jwtTokenUtil.validateToken(token)) {
            throw new ServiceException(StatusCode.TOKEN_INVALID);
        }

        String username = jwtTokenUtil.getUsernameFromToken(token);
        request.setAttribute("username", username);

        return true;
    }
}
